<template>
  <!-- 增加修改 -->
  <a-drawer width="50%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose">
    <a-divider orientation="left">
      <b>{{ formTitle }}</b>
    </a-divider>
    <a-form-model ref="form" :model="form" :rules="rules" :layout="'horizontal'">
      <a-row :gutter="24">
        <a-col
          :span="12">
          <a-form-model-item label="入库单号" prop="receiptNumber">
            <a-input v-model="form.receiptNumber" placeholder="请输入" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="客户名称" prop="customerName">
            <a-input v-model="form.customerName" placeholder="请输入" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col
          :span="12">
          <!-- externalBatchNumber -->
          <a-form-model-item label="外部批次号" prop="partPlanIncomingId">
            <a-tree-select
              v-model="form.partPlanIncomingId"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="partPlanIncomingList"
              placeholder="请选择"
              :replaceFields="replaceFields"
              tree-default-expand-all
              @select="selectExternalBatchNumber"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="内部批次号" prop="internalBatchNumber">
            <a-input v-model="form.internalBatchNumber" placeholder="请输入" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col
          :span="12">
          <a-form-model-item label="零件名称" prop="partName">
            <a-tree-select
              v-model="form.partName"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="processedTreeData"
              placeholder="请选择"
              :replaceFields="{
                children: 'children', title: 'title', key: 'key', value: 'value'
              }"
              tree-default-expand-all
              @select="selectPartName"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <!--
        :replaceFields="{
                children: 'children', title: 'inventoryCode', key: 'id', value: 'id'
              }"
        -->
        <a-col :span="12">
          <a-form-model-item label="零件图号" prop="partDrawingNo">
            <a-input v-model="form.partDrawingNo" disabled placeholder="请输入"/>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col
          :span="12">
          <a-form-model-item label="零件简称" prop="partAbbreviation">
            <a-tree-select
              v-model="form.partAbbreviation"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="deptOptions"
              placeholder="请选择"
              :replaceFields="replaceFields"
              tree-default-expand-all
              disabled
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="到货总数量" prop="totalQuantity">
            <a-input v-model="form.totalQuantity" placeholder="请输入" disabled/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col
          :span="12">
          <a-form-model-item label="正式件数量" prop="formalQuantity">
            <a-input v-model="form.formalQuantity" placeholder="请输入" disabled/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="试刀件数量" prop="testQuantity">
            <a-input v-model="form.testQuantity" placeholder="请输入" disabled/>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col
          :span="12">
          <a-form-model-item label="正式件仓库" prop="formalWarehouse">
            <a-input v-model="form.formalWarehouse" placeholder="请输入"/>

          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="试刀件仓库" prop="testWarehouse">
            <a-input v-model="form.testWarehouse" placeholder="请输入"/>

          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col
          :span="12">
          <a-form-model-item label="登记日期" prop="projectId">
            <a-date-picker v-model="form.planArrivalDate" :format="'YYYY-MM-DD'" :value-format="'YYYY-MM-DD HH:mm:ss'" disabled/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="登记人" prop="batchNumber">
            <a-input v-model="form.partDrawingNo" disabled placeholder="请输入"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="WMS仓库" prop="wmsName">
            <a-input v-model="form.wmsName" disabled placeholder="请输入"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="层位" prop="wmsStorey">
            <a-input v-model="form.wmsStorey" disabled placeholder="请输入"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col
          :span="24">
          <a-form-model-item label="入库说明" prop="batchNumber">
            <a-input v-model="form.partDrawingNo" placeholder="请输入" type="textarea"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-divider />

      <a-row :gutter="24" class="action-bar">
        <a-space>
          <a-button type="primary" class="editable-add-btn" @click="handleAddWarehouseReceiptItems">
            新增
          </a-button>
          <a-button class="editable-add-btn" @click="$refs.dialog.showModal(form.partDrawingNo)">
            选择已返厂
          </a-button>
          <a-button class="editable-add-btn" @click="handleDeleteBank">
            撤回删除
          </a-button>
        </a-space>
      </a-row>

      <a-row :gutter="24">

        <a-table bordered :data-source="form.handleAddWarehouseReceiptItems" :columns="columns" size="small">
          <!-- 序号列插槽 -->
          <template slot="indexSlot" slot-scope="text, record, index">
            {{ index + 1 }}
          </template>

          <template slot="testPiece" slot-scope="text, record">
            <a-select :value="text" @change="e=>handleChange(e, record, 'testPiece')">
              <a-select-option v-for="(e,i) in nametestPieceEnum" :value="e.value" :key="i">
                {{ e.label }}
              </a-select-option>
            </a-select>
            <!-- <editable-cell :enums="nametestPieceEnum" :text="text" @change="onCellChange(record.key, 'nametestPiece', $event)" /> -->
          </template>

          <template slot="partNumber" slot-scope="text, record">
            <!-- <editable-cell :text="text" @change="onCellChange(record.key, 'partNumber', $event)" /> -->
            <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'partNumber')"/>
          </template>

          <template slot="castingNumber" slot-scope="text, record">
            <!-- <editable-cell :text="text" @change="onCellChange(record.key, 'castingNumber', $event)" /> -->
            <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'castingNumber')"/>
          </template>

          <template slot="action" slot-scope="text, record">
            <a href="javascript:;" @click="handleDelete(record)" >删除</a>
          </template>
        </a-table>

      </a-row>
      <div class="bottom-control">
        <a-space>
          <a-button type="primary" :loading="submitLoading" @click="submitForm">
            保存
          </a-button>
          <a-button type="dashed" @click="cancel">
            取消
          </a-button>
        </a-space>
      </div>
    </a-form-model>
    <ReturnedFactoryDialogVue ref="dialog" @selectedRows="(selectedList)=>{form.handleAddWarehouseReceiptItems.push(...selectedList)}"/>
  </a-drawer>
</template>

<script>

// import { listAll } from '@/api/system/user'
import { partPlanIncomingPage } from '@/api/plan/incoming'
import { warehousingSerial } from '@/utils/serialUtils'
import { addWarehouseReceipt, updateWarehouseReceipt } from '@/api/materials/warehousing'
import { inventoryItem } from '@/api/baseData/inventory'

import ReturnedFactoryDialogVue from './ReturnedFactoryDialog.vue'

export default {
  name: 'CreateForm',
  components: {
    ReturnedFactoryDialogVue
  },
  props: {
    deptOptions: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      submitLoading: false,
      replaceFields: { children: 'children', title: 'batchNumber', key: 'id', value: 'id' },
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      formTitle: '',
      // 表单参数
      form: {
        userId: undefined,
        customerName: undefined,
        externalBatchNumber: undefined,
        internalBatchNumber: undefined,
        partName: undefined,
        partDrawingNo: undefined,
        partAbbreviation: undefined,
        totalQuantity: undefined,
        formalQuantity: undefined,
        remark: undefined,
        testQuantity: undefined,
        receiptNumber: undefined,
        testWarehouse: undefined,
        wmsStorey: undefined,
        wmsName: undefined,
        handleAddWarehouseReceiptItems: []
      },
      open: false,
      rules: {
        partPlanIncomingId: [
          { required: true, message: '外部批次号不能为空', trigger: 'blur' }
        ],
        internalBatchNumber: [
          { required: true, message: '内部批次号不能为空', trigger: 'blur' }
        ],
        partName: [
          { required: true, message: '零件名称不能为空', trigger: 'blur' }
        ]
      },
      columns: [
      {
        title: '序号',
        key: 'index',
        scopedSlots: { customRender: 'indexSlot' }, // 索引从0开始，+1后从1显示
        width: 80,
        align: 'center'
      },
        {
          title: '是否试刀件',
          dataIndex: 'testPiece',
          ellipsis: true,
          scopedSlots: { customRender: 'testPiece' },
          width: 80
        },
        {
          title: '实际零件内部编号',
          dataIndex: 'internalNumber',
          ellipsis: true,
          width: 80
        },
        {
          title: '零件号',
          dataIndex: 'partNumber',
          scopedSlots: { customRender: 'partNumber' },
          ellipsis: true,
          width: 80
        },
        {
          title: '铸件号',
          dataIndex: 'castingNumber',
          scopedSlots: { customRender: 'castingNumber' },
          width: 100
        },
        {
          title: '零件名称',
          dataIndex: 'partName',
          ellipsis: true,
          width: 100
        },
        {
          title: '操作',
          key: 'action',
          // fixed: 'right',
          width: 50,
          scopedSlots: { customRender: 'action' }
        }
      ],
      partPlanIncomingList: [],
      inventoryItemList: [],
      nametestPieceEnum: [
        { label: '是', value: 1 },
        { label: '否', value: 0 }
      ],
      deleteList: [],
      projectId: ''
    }
  },
  filters: {
  },
  created () {
    this.getPartPlanIncomingList()
    this.getinventoryItem()
  },
  computed: {
    // 处理后的数据，拼接 name 和 code
    processedTreeData () {
      const processData = (data) => {
        return this.inventoryItemList.map(item => ({
          title: `(${item.inventoryCode}|${item.inventoryName})`, // 拼接两个字段
          value: item.inventoryName,
          key: item.id,
          children: item.children ? processData(item.children) : undefined
        }))
      }
      return processData(this.rawTreeData)
    }

  },
  watch: {
    'form.handleAddWarehouseReceiptItems': {
      handler (newItems) {
        console.log('数组内对象属性变化', newItems)
        var testNum = 0
        var num = 0
        newItems.forEach((element, index) => {
          if (element.nametestPiece === 1) {
            element.internalNumber = 'S' + ++testNum
          } else {
            element.internalNumber = 'Z' + ++num
          }
        })

        this.form.formalQuantity = num
        this.form.testQuantity = testNum
        this.form.totalQuantity = (num + testNum)
      },
      deep: true // 深度监听
    }
  },
  methods: {
    // 撤销删除
    handleDeleteBank () {
      this.form.handleAddWarehouseReceiptItems.push(this.deleteList.pop())
    },
    // 删除
    handleDelete (record) {
      this.deleteList.push(this.form.handleAddWarehouseReceiptItems.filter(item => item.internalNumber === record.internalNumber)[0])
      this.form.handleAddWarehouseReceiptItems = this.form.handleAddWarehouseReceiptItems.filter(item => item.internalNumber !== record.internalNumber)
    },
    handleChange (e, info, ee) {
      console.info(e, info, ee)
      // info[ee] = e
      this.$set(info, ee, e)
    },
    // 选择外部批次号
    selectExternalBatchNumber (selectedKeys, info) {
      console.info((this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]))
      this.form.partDrawingNo = (this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]).partDrawingNo
      this.form.externalBatchNumber = (this.partPlanIncomingList.filter(it => it.id === selectedKeys)[0]).batchNumber
    },
    // 选择零件名称
    selectPartName (selectedKeys, info) {
      console.log('selected', selectedKeys, info, this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0])
      this.form.partAbbreviation = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).shortName
      this.form.unitOfMeasurement = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).unitOfMeasurement
      this.form.wmsName = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).wmsName
      this.form.wmsStorey = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).wmsStorey
    },
    // 来料交付计划列表
    getPartPlanIncomingList () {
      partPlanIncomingPage({ pageSize: 100, pageNum: 1 }).then(res => {
        this.partPlanIncomingList = res.rows
      })
    },
    // 存货档案
    getinventoryItem () {
      inventoryItem().then(res => {
        this.inventoryItemList = res.rows
      })
    },
    onClose () {
      this.open = false
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        receiptNumber: undefined,
        batchNumber: undefined,
        quantity: undefined,
        projectName: undefined,
        planArrivalDate: undefined,
        partDrawingNo: undefined,
        partName: undefined,
        remark: undefined,
        handleAddWarehouseReceiptItems: []
      }
    },
    // 添加零件
    handleAddWarehouseReceiptItems () {
      if (!this.form.partName) {
        this.$message.error(
                '请先选择零件名称',
                3
              )
              return
      }
      this.form.handleAddWarehouseReceiptItems.push({
          nametestPiece: 0,
          partNumber: '',
          internalNumber: '',
          castingNumber: '',
          partName: this.form.partName

      })
    },
     /** 新增按钮操作 */
    handleAdd (projectId) {
      if (!projectId) {
        this.$message.error(
                '请先选择项目',
                3
              )
        return
      }
      this.reset()
      this.$emit('select-tree')
      this.open = true
      this.formTitle = '毛坯入库单'
      this.projectId = projectId
      this.form = {
        userId: undefined,
        customerName: undefined,
        externalBatchNumber: undefined,
        internalBatchNumber: undefined,
        partName: undefined,
        partDrawingNo: undefined,
        partAbbreviation: undefined,
        totalQuantity: undefined,
        formalQuantity: undefined,
        remark: undefined,
        testQuantity: undefined,
        receiptNumber: warehousingSerial(),
        testWarehouse: undefined,
        handleAddWarehouseReceiptItems: [],
        projectId: projectId,
        partPlanIncomingId: undefined
      }
    },
    /** 修改按钮操作 */
    handleUpdate (row, ids) {
      this.reset()
      this.$emit('select-tree')
      // const userId = row ? row.userId : ids
      // getUser(userId).then(response => {
      //   this.form = response.data
      //   this.postOptions = response.posts
      //   this.roleOptions = response.roles
      //   this.form.postIds = response.postIds
      //   this.form.roleIds = response.roleIds
      //   this.open = true
      //   this.formTitle = '修改用户'
      //   this.form.planArrivalDate = ''
      // })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.form.id !== undefined) {
            updateWarehouseReceipt(this.form).then(response => {
              this.$message.success(
                '修改成功',
                3
              )
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            addWarehouseReceipt(this.form).then(response => {
              this.$message.success(
                '新增成功',
                3
              )
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
